package beanstao.util.store.database;

import java.util.ArrayList;
import java.util.Iterator;

import beanstao.util.Formula;
import beanstao.util.Strings;
import beanstao.util.store.database.interfaces.IExpression;


/**
 * 面向Select输出的字段
 * 
 */
public class Column implements IExpression
{
	private SqlFunc _func;
	private final ArrayList<Formula> _sqlFields = new ArrayList<Formula>();
	private String _as;

	public Column()
	{
	}

	public void setFunction(SqlFunc function)
	{
		_func = function;
	}

	public void append(Formula... sqlFields)
	{
		for (Formula formula : sqlFields)
			_sqlFields.add(formula);
	}

	public void as(String asName)
	{
		_as = asName;
	}

	@Override
	public void render(StringBuilder sb, Fields columns)
	{
		if (_func != null)
		{
			_func.render(sb, columns);
			sb.append("(");
		}
		for (Iterator<Formula> it = _sqlFields.iterator(); it.hasNext();)
		{
			sb.append(it.next().toStringBuilder());
			if (it.hasNext())
				sb.append(",");
		}
		if (_func != null)
			sb.append(")");
		if (!Strings.isEmpty(_as))
			sb.append(" AS ").append(_as).append(" ");
	}

	public StringBuilder toStringBuilder(Fields columns)
	{
		StringBuilder sb = new StringBuilder();
		this.render(sb, columns);
		return sb;
	}

	public String toSql(Fields columns)
	{
		StringBuilder sb = new StringBuilder();
		this.render(sb, columns);
		return sb.toString();
	}

}
